import { login, logout, getInfo } from "@/api/login";
import { getToken, setToken, removeToken } from "@/utils/auth";

const user = {
  state: {
    token: getToken(),
    name: "",
    avatar: "",
    roles: [],
    permissions: [],
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token;
    },
    SET_NAME: (state, name) => {
      state.name = name;
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar;
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles;
    },
    SET_PERMISSIONS: (state, permissions) => {
      state.permissions = permissions;
    },
  },

  actions: {
    // 登录
    Login({ commit }, userInfo) {
      const username = userInfo.username.trim();
      const password = userInfo.password;
      const code = userInfo.code;
      const uuid = userInfo.uuid;
      return new Promise((resolve, reject) => {
        login(username, password, code, uuid)
          .then((res) => {
            setToken(res.token);
            commit("SET_TOKEN", res.token);
            resolve();
          })
          .catch((error) => {
            reject(error);
          });
      });
    },

    // 获取用户信息
    GetInfo({ commit, state }) {
      return new Promise((resolve, reject) => {
        const res = {
          msg: "操作成功",
          code: 200,
          permissions: [
            "system:post:list",
            "flowable:form:query",
            "system:menu:query",
            "system:menu:list",
            "system:config:list",
            "system:listener:list",
            "system:role:list",
            "system:deployment:add",
            "monitor:job:list",
            "system:user:query",
            "system:dept:list",
            "system:config:query",
            "tool:gen:query",
            "system:listener:add",
            "flowable:form:remove",
            "flowable:form:edit",
            "system:dept:query",
            "system:dict:list",
            "tool:build:list",
            "monitor:job:query",
            "flowable:form:add",
            "system:deployment:edit",
            "system:expression:list",
            "tool:gen:preview",
            "system:user:list",
            "system:notice:list",
            "system:dict:query",
            "monitor:online:query",
            "system:notice:query",
            "system:expression:query",
            "monitor:online:list",
            "flowable:form:list",
            "tool:gen:list",
            "system:deployment:remove",
            "system:role:query",
            "system:post:query",
            "system:listener:query",
          ],
          roles: ["common"],
          user: {
            createBy: "admin",
            createTime: "2022-12-11 16:51:52",
            updateBy: null,
            updateTime: null,
            remark: "测试员",
            params: {
              "@type": "java.util.HashMap",
            },
            userId: 2,
            deptId: 105,
            userName: "tony",
            nickName: "老李",
            email: "ry@qq.com",
            phonenumber: "15666666666",
            sex: "1",
            avatar: "/profile/avatar/2023/10/23/blob_20231023092141A011.png",
            password:
              "$2a$10$Zr6o0KSInOfo1Yt3xq1NnOuhuiQ0pjiWE2k.zNHbEyzAkEF0ZcVZ.",
            status: "0",
            delFlag: "0",
            loginIp: "127.0.0.1",
            loginDate: "2023-10-27T13:45:16.000+08:00",
            dept: {
              createBy: null,
              createTime: null,
              updateBy: null,
              updateTime: null,
              remark: null,
              params: {
                "@type": "java.util.HashMap",
              },
              deptId: 105,
              parentId: 101,
              ancestors: "0,100,101",
              deptName: "测试部门",
              orderNum: 3,
              leader: "若依",
              phone: null,
              email: null,
              status: "0",
              delFlag: null,
              parentName: null,
              children: [],
            },
            roles: [
              {
                createBy: null,
                createTime: null,
                updateBy: null,
                updateTime: null,
                remark: null,
                params: {
                  "@type": "java.util.HashMap",
                },
                roleId: 2,
                roleName: "普通角色",
                roleKey: "common",
                roleSort: 2,
                dataScope: "1",
                menuCheckStrictly: false,
                deptCheckStrictly: false,
                status: "0",
                delFlag: null,
                flag: false,
                menuIds: null,
                deptIds: null,
                permissions: [
                  "system:post:list",
                  "flowable:form:query",
                  "system:menu:query",
                  "system:menu:list",
                  "system:config:list",
                  "system:listener:list",
                  "system:role:list",
                  "system:deployment:add",
                  "monitor:job:list",
                  "system:user:query",
                  "system:dept:list",
                  "system:config:query",
                  "tool:gen:query",
                  "system:listener:add",
                  "flowable:form:remove",
                  "flowable:form:edit",
                  "system:dept:query",
                  "system:dict:list",
                  "tool:build:list",
                  "monitor:job:query",
                  "flowable:form:add",
                  "system:deployment:edit",
                  "system:expression:list",
                  "tool:gen:preview",
                  "system:user:list",
                  "system:notice:list",
                  "system:dict:query",
                  "monitor:online:query",
                  "system:notice:query",
                  "system:expression:query",
                  "monitor:online:list",
                  "flowable:form:list",
                  "tool:gen:list",
                  "system:deployment:remove",
                  "system:role:query",
                  "system:post:query",
                  "system:listener:query",
                ],
                admin: false,
              },
            ],
            roleIds: null,
            postIds: null,
            roleId: null,
            admin: false,
          },
        };
        const user = res.user;
        const avatar =
          user.avatar == "" || user.avatar == null
            ? require("@/assets/images/profile.jpg")
            : process.env.VUE_APP_BASE_API + user.avatar;
        if (res.roles && res.roles.length > 0) {
          // 验证返回的roles是否是一个非空数组
          commit("SET_ROLES", res.roles);
          commit("SET_PERMISSIONS", res.permissions);
        } else {
          commit("SET_ROLES", ["ROLE_DEFAULT"]);
        }
        commit("SET_NAME", user.userName);
        commit("SET_AVATAR", avatar);
        resolve(res);
      });
    },

    // 退出系统
    LogOut({ commit, state }) {
      return new Promise((resolve, reject) => {
        logout(state.token)
          .then(() => {
            commit("SET_TOKEN", "");
            commit("SET_ROLES", []);
            commit("SET_PERMISSIONS", []);
            removeToken();
            resolve();
          })
          .catch((error) => {
            reject(error);
          });
      });
    },

    // 前端 登出
    FedLogOut({ commit }) {
      return new Promise((resolve) => {
        commit("SET_TOKEN", "");
        removeToken();
        resolve();
      });
    },
  },
};

export default user;
